from flask_restful import Resource
import os
from flask import jsonify, request

# 获取当前文件的目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

# 定义相对路径，并转换为绝对路径
UPLOAD_FOLDER = os.path.join(BASE_DIR, '../data/question_sets')

# 确保目录存在
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)


class FileContent(Resource):
    def post(self):
        # 从请求体中获取文件路径
        data = request.get_json()
        file_name = data.get('file_name')
        file_path = os.path.join(UPLOAD_FOLDER, file_name)
        if not os.path.exists(file_path):
            return {"message": "File not found"}, 404

        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.readlines()

        # 格式化文件内容
        formatted_content = [
            {"label": line.strip(), "value": line.split(',', 1)[1].strip()}  # 完整内容为label，第二列内容为value
            for line in content if line.strip()  # 确保不为空行
        ]

        return jsonify({"questions": formatted_content})
